package com.example.demo.controller;


import com.example.demo.core.entity.Role;
import com.example.demo.core.service.RoleService;
import com.example.demo.domain.User;
import com.example.demo.service.UserService;
import com.example.demo.util.ParseUsername;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONArray;
import net.sf.json.JSONException;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping
@CrossOrigin
@Slf4j
public class UserController {
    @Autowired
    private UserService userService;

    @Autowired
    private RoleService roleService;

    private List<User> userList;

    /**
    * @Description:  获取全部用户,用于用户导出
    * @Param:  无
    * @return:  全部用户
    * @Author: wangze
    */
    @PreAuthorize("hasPermission('userList','users:users:export')")
    @GetMapping(value = "/all-users")
    public List<User> getAllUsers() {
        return userService.getAllUsers();
    }

    /**
    * @Description: 导入excel用户
    * @Param:  excelData: 表格数据
    * @return:  是否全部导入成功
    * @Author: wangze
    */
    @PreAuthorize("hasPermission('userList','users:users:import')")
    @PostMapping(value = "/import-users")
    public boolean importUsers(@RequestBody String excelData){
        com.alibaba.fastjson.JSONObject j1 = com.alibaba.fastjson.JSONObject.parseObject(excelData);
        userList= com.alibaba.fastjson.JSONObject.parseArray(j1.getJSONArray("excelData").toJSONString(),User.class);
        for(int i=0;i<userList.size();i++){
            User user=userService.addUser(userList.get(i));
            if(user==null)
                return false;
        }
        log.info("管理员{}通过excel导入了{}个用户", ParseUsername.getUser(),userList.size());
        return true;
    }

    /**
     * @Description:  获取用户列表
     * @Param:  nowpage：当前页码
     * @Param: pagesize：页码大小
     * @Param: select：选择的搜索种类
     * @Param: searchContent：搜索内容
     * @return:
     * @Author: wangze
     */
    @PreAuthorize("hasPermission('userList','users:users:list')")
    @GetMapping(value = "/users")
    public String getUserList(@RequestParam("nowPage")Integer nowpage, @RequestParam("pageSize")Integer pagesize,
                                      @RequestParam("select")String select, @RequestParam("searchContent")String searchContent){
        if(select.equals("workNumber")){
            userList=userService.findUserByWorkNumber(searchContent);
        }
        else if(select.equals("employeeName")){
            userList=userService.findUserByName(searchContent);
        }else if(select.equals("department")){
            userList=userService.findUserByDepartment(searchContent);
        }else{
            userList=userService.getUsersByKeyword(searchContent);
        }
        JSONArray jsonArray = new JSONArray();
        JSONObject jsonObject=new JSONObject();
        jsonObject.put("number",userList.size());
        jsonArray.add(jsonObject);
        List<User> users = userList.subList((nowpage - 1) * pagesize,Math.min( nowpage * pagesize,userList.size()));
        for (User temp:users){
            JSONObject jsonObject1=new JSONObject();
            jsonObject1.put("userId",temp.getUserId());
            jsonObject1.put("workNumber",temp.getUsername());
            jsonObject1.put("name",temp.getName());
            jsonObject1.put("department",temp.getDepartment());
            jsonObject1.put("phone",temp.getPhone());
            jsonObject1.put("sex",temp.getSex());
            jsonObject1.put("age",temp.getAge());
            jsonObject1.put("role",temp.getAuth());
            jsonObject1.put("roleId",temp.getRoleId());
            jsonArray.add(jsonObject1);
        }
        return jsonArray.toString();
    }

    /**
    * @Description: 添加用户
    * @Param:  user: 前段传递的用户实体
    * @return:  提示信息
    * @Author: wangze
    */
    @PreAuthorize("hasPermission('userList','users:users:add')")
    @PostMapping("/user")
    public String addUser(@RequestBody User user) throws JSONException {
        try{
            user.setPassword(user.getUsername());
            if(userService.addUser(user)==null)
                throw new Exception();
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("status","success");
            jsonObject.put("msg","注册成功");
            log.info("管理员{}添加了用户{}", ParseUsername.getUser(),user);
            return jsonObject.toString();
        }catch (Exception e){
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("status","error");
            jsonObject.put("msg","该用户名已被注册");
            log.error("管理员{}添加用户{}失败。\n" + e,ParseUsername.getUser(),user );
            return jsonObject.toString();
        }
    }

    /**
     * @Description: 根据ID删除用户
     * @Param:  id: 用户ID
     * @return:  无
     * @Author: wangze
     */
    @PreAuthorize("hasPermission('userList','users:users:delete')")
    @DeleteMapping(value = "/user")
    public String deleteUserById(@RequestParam("userId")Integer id){
        try{
            User user = userService.getById(id);
            userService.deleteUserById(id);
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("status",200);
            jsonObject.put("msg","删除用户成功");
            log.info("管理员{}删除了用户{}", ParseUsername.getUser(),user);
            return jsonObject.toString();
        }catch (Exception e) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("status",400);
            jsonObject.put("msg","删除用户失败，该用户不存在!");
            log.error("管理员{}删除用户失败。\n"+ e,ParseUsername.getUser() );
            return jsonObject.toString();
        }
    }

    /**
    * @Description: 编辑用户
    * @Param:  user：前端传来的用户实体
    * @return:  无
    * @Author: wangze
    */
    @PreAuthorize("hasPermission('userList','users:users:update')")
    @PutMapping(value = "/user")
    public User updateUserById(@RequestBody User user){
        log.info("管理员{}更新了用户{}信息",ParseUsername.getUser(),user);
        return userService.updateUser(user);
    }

    /**
    * @Description: 根据ID查找用户(双端都用到)
    * @Param:  id：用户ID
    * @return:  无
    * @Author: wangze
    */
    @PreAuthorize("hasPermission('users','users:permissions:basic')")
    @GetMapping(value = "/user")
    public User getUserById(@RequestParam("userId") Integer id) { return userService.getById(id); }

    /**
    * @Description: 根据职工工号查找用户(所有用户都拥有的权限)
    * @Param:   worknumber: 职工工号
    * @return:  用户
    * @Author: wangze
    */
    @PreAuthorize("hasPermission('users','users:permissions:basic')")
    @GetMapping(value = "/user/{username}")
    public User getUserByUsername(@PathVariable String username){
        return userService.getByUsername(username);
    }

    /**
    * @Description: 超级管理员重置用户密码
    * @Param:  id: 用户ID
    * @return:  提示信息
    * @Author: wangze
    */
    @PreAuthorize("hasPermission('userList','users:users:reset')")
    @GetMapping(value = "/user/reset")
    public String resetPassword(@RequestParam("userId") Integer id){
        try{
            userService.resetPassword(id);
            User user=userService.getById(id);
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("status",200);
            jsonObject.put("msg","重置用户密码成功");
            log.info("管理员{}重置用户{}密码成功", ParseUsername.getUser(),user);
            return jsonObject.toString();
        }catch (Exception e) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("status",400);
            jsonObject.put("msg","重置用户密码失败");
            log.info("管理员{}重置用户密码失败", ParseUsername.getUser());
            return jsonObject.toString();
        }
    }

    /**
    * @Description: 分配角色
    * @Param:  id: 用户ID
     * @Param: roleId: 角色ID
    * @return: 角色信息
    * @Author: wangze
    */
    @PreAuthorize("hasPermission('userList','users:users:allot')")
    @PutMapping(value = "/user/{id}/role")
    public Role allotRole(@PathVariable Integer id,@RequestParam("roleId") String roleId){
        User user=userService.getById(id);
        Integer temp=Integer.parseInt(roleId);
        Role role=roleService.getRoleById(temp);
        user.setRoleId(temp);
        user.setAuth(role.getName());
        userService.updateUser(user);
        return role;
    }
}
